package 力扣;

/**
 * @author yyq
 * @create 2022-03-09 18:47
 */
public class leetcode19 {
    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        head.next=new ListNode(2);
        head.next.next=new ListNode(3);
        head.next.next.next=new ListNode(4);
        head.next.next.next.next=new ListNode(5);
        removeNthFromEnd(head,2);
    }
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // n为两个指针之间的距离
        ListNode forward=null;
        ListNode back=null;
        // 只有一个节点，肯定是删除那个节点了
        if(head.next==null) return null;
        // 初始化forward，forward指向第n个节点
        for (int i = 0; i <= n; i++) {
            if(forward==null) forward=head;
            else forward=forward.next;
        }
        // 一起移动两个指针，直到forwar==null
        while(forward!=null){
            if(back==null) back=head;
            else back=back.next;
            forward=forward.next;
        }
        //  删除第一个节点
        if(back==null) {
            head=head.next;
        }
        else {
            // 删除最后一个节点
            if(back.next.next==null) back.next=null;
            // 删除中间节点
            else back.next=back.next.next;
        }
        return head;
    }
}
